package com.jingdianjichi.auth.application.interceptor;

import com.jingdianjichi.auth.application.context.LoginContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
  *自定义登录拦截器,其实这个id,我们在远程调用的时候是可以传递过来的,我们在存入上下文也是可以的,但是我们这里就是去学习OpenFeign的拦截器奥亲
  */
public class LoginInterceptor implements HandlerInterceptor {

    private static final String LOGIN_ID="loginId";

    //获得请求头亲,我们去解析即可,在进入请求前的亲
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginId = request.getHeader(LOGIN_ID);

        //放入上下文亲
        LoginContextHolder.set(LOGIN_ID,loginId);      //这时我们最好提供一个工具类和ThreadLocal去做交互亲

        return true;    //放行亲
    }

    //这个是请求后的,我们要做上下文清除的,否则在次进来的时候会上下文混乱的
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContextHolder.remove();
    }
}
